const { CateParamError } = require("../constant/err.type");

const verifyModifyParam = async (ctx, next) => {
  if (!ctx.request.body) {
    console.error("未携带参数");
    ctx.app.emit("error", CateParamError, ctx);
    return;
  } else {
    const { id, typeName } = ctx.request.body;
    if (!id) {
      console.error("请携带id参数");
      ctx.app.emit("error", CateParamError, ctx);
      return;
    }
    if (!typeName) {
      console.error("typeName是必需参数！", typeName);
      ctx.app.emit("error", CateParamError, ctx);
      return;
    }

    await next();
  }
};

const verifyAddParam = async (ctx, next) => {
  if (!ctx.request.body) {
    console.error("未携带参数");
    ctx.app.emit("error", CateParamError, ctx);
    return;
  } else {
    const { typeName } = ctx.request.body;
    if (!typeName) {
      console.error("typeName是必需参数！", typeName);
      ctx.app.emit("error", CateParamError, ctx);
      return;
    }

    await next();
  }
};

const verifyDeleteId = async (ctx, next) => {
  console.log(ctx.request.body, "id");
  if (ctx.request.body && ctx.request.body.id) {
    await next();
  } else {
    ctx.app.emit("error", CateParamError, ctx);
    return;
  }
};

const verifyDeleteIds = async (ctx, next) => {
  console.log(ctx.request.body, "---ids");

  if (ctx.request.body && ctx.request.body.ids) {
    await next();
  } else {
    ctx.app.emit("error", CateParamError, ctx);
    return;
  }
};

const verifyQueryParams = async (ctx, next) => {
  const requsetObj = {};

  if (ctx.request.body) {
    const { page, size, typeName } = ctx.request.body;
    if (typeName) {
      requsetObj.typeName = typeName;
    }
    if (page) {
      requsetObj.page = page;
    } else {
      requsetObj.page = 1;
    }
    if (size) {
      requsetObj.size = size;
    } else {
      requsetObj.size = 10;
    }
  } else {
    requsetObj.page = 1;
    requsetObj.size = 10;
  }

  ctx.request.body = requsetObj;
  await next();
};

module.exports = {
  verifyAddParam,
  verifyModifyParam,
  verifyDeleteId,
  verifyDeleteIds,
  verifyQueryParams,
};
